package com.zx.crowdfunding.mvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.zx.crowdfunding.constant.CrowdFundingConstant;
import com.zx.crowdfunding.entity.Admin;
import com.zx.crowdfunding.exception.AccessForbiddenException;

/**
 * 自定义登录拦截器
 * @author 郑雪
 * @date 2021-12-08
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		// 1.通过request对象获取Session对象
		HttpSession session = request.getSession();
		
		// 2.从Session域中获取Admin对象
		Admin admin = (Admin) session.getAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_ADMIN);
		
		// 3.判断Admin对象是否为空
		if(admin == null){
			
			// 4.抛出异常
			throw new AccessForbiddenException(CrowdFundingConstant.MESSAGE_ACCESS_FORBIDDEN);
		}
		
		// 5.如果Admin对象不为null，则返回true放行
		return true;
	}

}
